from sgmllib import SGMLParser
"""
   From what I can tell of the OFX format, there are 2 types of tags.  Data & container tags.
   Data tags are <blah>SomeValue[\n\s<]{1,}
   And list tags consist of one or more Data tags.   
    <foo>
        <blah>SumVal
        <Ich>OtherVal
        <bar>LastVal
    </foo>
    
    All data tags are contained into list tags and list tags can contain one or more of the same data tag, in which case the parser pushes all of these multiple
    data tags.
    Example
    <foo>
        <blah>SumVal
        <blah>OtherVal
        <blah>LastVal
    </foo>
    {foo: [SumVal, OtherVal, LastVal] }
    
    Note that the majority of cases, that duplicate child elements are often list tags in of themselves, so the processed data will look like
    {parentKey:[ {k:v,k2:v,k3:v},{k:v,k2:v,k3:v},{k:v,k2:v,k3:v} ]}
   
"""


class QFXParser(SGMLParser):
    """
        OFX to dict/list translator
                
    """
    def reset(self):
        """
            Bring self & super to a consistent state
        """
        SGMLParser.reset(self)
        self.myQueue = []
        self.tagData = []
        self.tree = {}
        self.myCurrentTag = ""
        
    def unknown_starttag(self, tag, attrs):        
        self.myQueue.append({tag:None})
        self.myCurrentTag = tag

    
    def handle_data(self,data):
        if(data != None and data.strip() != ""):
            self.myQueue[-1][self.myCurrentTag] = data


    def unknown_endtag(self, tag):
        
        newNode = {}
        newQueue = []
        
        
        while not tag in self.myQueue[-1]:
            node = self.myQueue.pop()
            for key in node.keys():
                if key in newNode: #the Parent node already has this value, in which case we need to conver the parents container to an list
                    if hasattr(newNode[key], ("append")) == False : #then we need to create an array
                        firstNode = newNode[key]
                        newNode[key] = [firstNode,node[key]]                        
                    else:
                        newNode[key].append(node[key])
                else:
                    newNode.update(node)
            
            
        self.myQueue[-1][tag] = newNode
